package aos2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class MyClient {

	public static void main(String[] args) {
		try {
//			Properties serverlist = new Properties();
//			serverlist.load(new FileReader(new File("serverlist.properties")));
//			
//			Set<Entry<Object, Object>> entrySet = serverlist.entrySet();
//			Socket[] sockets = new Socket[entrySet.size()]; 
//			int j=0;
//			for(Entry<Object, Object> e : entrySet){
//				sockets[j]	= new Socket((String)e.getKey(), (Integer)e.getValue());
//				j++;
//			}
			Socket[] sockets = new Socket[4];
			sockets[0]	= new Socket("localhost", 5000);
			sockets[1] = new Socket("localhost", 5001);
			sockets[2] = new Socket("localhost", 5002);
			//Socket tailSocket = new Socket("localhost", 5003);
			OutputStream os = null;
			PrintWriter pw = null;
			BufferedReader br = null;
			
			//BufferedReader tailbr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			for(int i =0; i < 50; i++){
				int x = (int)Math.floor(Math.random()*3);
				
				Socket socket = sockets[x];
				System.out.println("sending to server : " + socket.getPort());
				os = socket.getOutputStream();
				pw = new PrintWriter(os);
				br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			Request req = new Request();
			
			req.setMessage("This is my "+ i +"th request!");
			int y = (int)Math.floor(Math.random()*2);
			RequestType[] reqstyp = {RequestType.CLIENT_WRITE, RequestType.CLIENT_READ};
			//req.setType(reqstyp[y]);
			req.setType(RequestType.CLIENT_WRITE);
			req.setFileName("file"+y+".txt");
			pw.println(req.toString());
			pw.flush();
			String res = null;
			while((res = br.readLine()) != null){
				if(res.equals("Bye.")){
					break;
				}else{
					System.out.println(res);
				}
			}
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		/*	String confirm = null;
			while((confirm = tailbr.readLine())!= null){
				System.out.println("FROM TAIL" + confirm);
			}
			*/
			pw.close();
			os.close();
			br.close();
			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
